//
//  GXSearchBarViewController.m
//  GXLanOuADemo
//
//  Created by 甘霞 on 15/11/2.
//  Copyright © 2015年 甘霞. All rights reserved.
//

#import "GXSearchBarViewController.h"
#import "GXiaNetHandle.h"
#import "WebSiteManager.h"
#import "GXSearchResourceViewController.h"
#import "UIScrollView+EmptyDataSet.h"
#import "WebSiteManager.h"

@interface GXSearchBarViewController () <UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, copy) NSString *chineseName;
@property (nonatomic, copy) NSString *searchHight;
@property (nonatomic, retain) NSMutableArray *suggestSearchArr;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, retain) UIButton *cancelBtn;

@end

@implementation GXSearchBarViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    [self.searchBar setHidden:NO];
    
    NSArray *temp = self.tabBarController.view.subviews;
    UIView *tabbarView = temp[2];
    [UIView animateWithDuration:1 animations:^{
        tabbarView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 49);
    }];
}

#pragma mark - 视图已经出现
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    //创建搜索框
    [self createSearchBar];
    
    //创建 tableView
    [self createTableView];
    
    //导航右按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon-cancel-search"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClick:)];
    
    //  导航栏左按钮
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-yuyin"] style:UIBarButtonItemStylePlain target:self action:@selector(iFLYAction:)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"语音" style:UIBarButtonItemStylePlain target:self action:@selector(iFLYAction:)];
}

#pragma mark - 导航栏左按钮
- (void)iFLYAction:(UIBarButtonItem *)btn {
    
}

#pragma mark - 创建搜索框
- (void)createSearchBar {
    //创建搜索框
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 60, 0)];
    //风格
    [self.searchBar setSearchBarStyle:UISearchBarStyleDefault];
    //占位符
    self.searchBar.placeholder = @"搜索内容和专题";
    //边框
    self.searchBar.layer.borderWidth = 1;
    //圆角
    self.searchBar.layer.cornerRadius = 20;
    //layer
    self.searchBar.layer.masksToBounds = YES;
    //设置为导航栏子视图
    self.navigationItem.titleView = self.searchBar;
    //代理
    self.searchBar.delegate = self;
    //第一响应
    [self.searchBar becomeFirstResponder];
}

#pragma mark -- searchBar文字输入完成动态请求网络
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    //如果有搜索文本 右按钮名称为搜索
    if (searchBar.text.length > 0){
        //设置分割线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }
    //如果没有搜索哦文本 右按钮名称为取消
    else if(searchBar.text.length == 0){
        //视图刷新
        [self.tableView reloadData];
        self.navigationItem.rightBarButtonItem.title = @"取消";
    }
    //转码
    self.chineseName = searchBar.text;
    self.searchHight = searchBar.text;
    //转码
    self.name = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self.chineseName, NULL, NULL,  kCFStringEncodingUTF8));
    NSString *URLbody = [NSString stringWithFormat:@"%@",self.name];
    //做网络请求
    [self creatData:URLbody];
    //视图∫刷新数据
    [self.tableView reloadData];
}

#pragma mark - 视图将要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //隐藏搜索框
    self.searchBar.hidden = YES;
    //当视图将要消失时 将搜索框文本置空
    self.searchBar.text = @"";
    //将 name 置空
    self.name = @"";
    //失去第一响应
    [self.searchBar resignFirstResponder];
}

#pragma mark - 搜索键盘中的搜索按钮响应
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    //收键盘
    [self.searchBar endEditing:YES];
    //跳转至搜索结果页面
    GXSearchResourceViewController *resultVC = [[GXSearchResourceViewController alloc] init];
    //不隐藏导航栏
    self.navigationController.navigationBarHidden = NO;
    //属性传值
    resultVC.str = self.name;
    //push
    [self.navigationController pushViewController:resultVC animated:YES];
}

#pragma mark --searchBar 右边的取消按钮按钮的点击事件
- (void)buttonClick:(UIBarButtonItem *)button{
    //返回上一个界面
    //导航栏设置
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    self.searchBar.hidden = YES;
    //pop
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 搜索框大概完成输入
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [self.tableView reloadData];
    return YES;
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}

#pragma mark - 推荐搜索网络请求
- (void)creatData:(NSString *)URLBody {
    //请求数据
    NSString *url = [NSString stringWithFormat:kSearchSuggestWeb, URLBody];
    [GXiaNetHandle getUrl:url cookie:nil success:^(id result) {
        //将请求到的推荐搜索添加到数组中
        self.suggestSearchArr = result[@"suggestions"];
        //刷新视图
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        NSLog(@"error:%@", error);
    }];
}

#pragma mark - 创建 tableView
- (void)createTableView {
    [self createTableViewWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"HAHA"];
}

#pragma mark - tableView 代理/数据源实现方法
#pragma mark - 一共有几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.suggestSearchArr.count;
}

#pragma mark - tableView 每行显示什么内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HAHA"];
    cell.textLabel.text = self.suggestSearchArr[indexPath.row];
    
#pragma mark - 关键字高亮
    NSMutableAttributedString *AttributeStr = [[NSMutableAttributedString alloc] initWithString:self.suggestSearchArr[indexPath.row]];
    NSRange range = [self.suggestSearchArr[indexPath.row] rangeOfString:self.searchHight];
    [AttributeStr setAttributes:@{NSForegroundColorAttributeName:[UIColor colorWithRed:35/255.0 green:172/255.0 blue:183/255.0 alpha:1], NSFontAttributeName:[UIFont systemFontOfSize:17]} range:range];
    cell.textLabel.attributedText = AttributeStr;
    
    return cell;
}

#pragma mark - tabelView 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取消选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //将搜索框的文本设置为选中行的文本
    self.searchBar.text = self.suggestSearchArr[indexPath.row];
}

#pragma mark - 滚动时 搜索框失去第一响应
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
}

#pragma mark - 当数据为空时显示的图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return [UIImage imageNamed:@"icon-search-article"];
}

#pragma mark - 当数据为空时显示的字符
-(NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"搜索内容和专题";
    NSDictionary *str = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0f]};
    return [[NSAttributedString alloc] initWithString:text attributes:str];
}

@end
